//
//  YSGNurseAppointmentOrderDetailsController.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/3/17.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit


class YSGNurseAppointmentOrderDetailsController: BaseViewController {
    
    var appointmentId :String?
    var orderId :String?
    var isListPay : Bool = false
    
    
    private var payVm = PayViewModel(order: PayOrderModel())
    
    
    @IBOutlet var tableViewHeaderView: UIView!{
        didSet{
            tableViewHeaderView.frame = CGRect(x: 0, y: 0, width: screenW, height: 51)
        }
    }
    @IBOutlet weak var payButton: UIButton!
    
    @IBOutlet weak var TipView: UIView!
    
    @IBOutlet weak var nurseView: UIView!
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var sexLabel: UILabel!
    
    @IBOutlet weak var phoneLabel: UILabel!
    
    @IBOutlet weak var ageLabel: UILabel!
    
    @IBOutlet weak var addressLabel: UILabel!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    
    @IBOutlet weak var isEyeRedLabel: UILabel!
    
    @IBOutlet weak var isSecretionLabel: UILabel!
    
    @IBOutlet weak var isTrichiasisLabel: UILabel!
    
    @IBOutlet weak var isUnobstructedLabel: UILabel!
    //
    @IBOutlet weak var isSutureLabel: UILabel!
    
    
    //合计多少钱
    @IBOutlet weak var tableViewBottomLabel: UILabel!
    //合计视图
    @IBOutlet var tableViewBottomView: UIView!{
        didSet{
            tableViewBottomView.frame = CGRect(x: 0, y: 0, width: screenW, height: 58.5)
        }
    }
    //合计多少钱
    @IBOutlet weak var sumMoneyLabel: UILabel!
    //运费
    @IBOutlet weak var freightLabel: UILabel!
    
    //护士名称
    @IBOutlet weak var nurseNameLabel: UILabel!
    
    //电话按钮
    @IBOutlet weak var phoneButton: UIButton!{
        didSet{
            phoneButton.layoutButton(with: .imageRight)
        }
    }
    @IBOutlet weak var agreeButton: UIButton!
    
    @IBAction func agreeButtonAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    @IBOutlet weak var agreementLabel: UILabel!{
        didSet{
            agreementLabel.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(agreeLabelClicked))
            agreementLabel.addGestureRecognizer(tap)
        }
    }
    //服务协议
    @objc func agreeLabelClicked(){
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
        agreementView.showString(type: model?.chargeItemCode ?? "")
    }
    
    @IBOutlet weak var tableView: UITableView!{
        didSet{
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(YSGNurseAppointmentConsumablesCell.nibForCell(), forCellReuseIdentifier: YSGNurseAppointmentConsumablesCell.reuseIdentifier())
        }
    }
    
    @IBOutlet weak var projectTitleLabel: UILabel!
    
    var model : YSGNurseAppointmentInfoDetailsModel?
    
    let viewModel : YSGNurseAppointmentInfoDetailsViewModel = YSGNurseAppointmentInfoDetailsViewModel()
    
    private lazy var starRatingView: YSGNurseAppointMentStarRatingView = {

        let view = UINib.loadViewFrom(YSGNurseAppointMentStarRatingView.self)
        view.frame = CGRect(x: 0, y: 0, width: screenW, height: 226)
        view.starRatingView.clickEnable = false
        view.starRatingView.slideEnable = false
        view.textView?.isEditable = false
        return view
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNotification()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "护理预约"

        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
        
    }
    
    @objc func loadData() {
        viewModel.getProjectDetails(appointmentId: appointmentId!) {[weak self] model, errorMsg, code in
            self?.tableView.mj_header?.endRefreshing()
            if (model != nil){
                ///数据绑定
                ///

                
                
                self?.tableView.reloadData()
                self?.model = model
                self?.nameLabel.text = "姓名: " + (model?.patientName ?? "")
                self?.sexLabel.text = "性别: " + (model?.sex ?? "")
                self?.ageLabel.text = "年龄: " + (model?.age ?? "")
                self?.phoneLabel.text = "联系方式: " + (model?.patientPhone ?? "")
                self?.addressLabel.text = "地址: " + (model?.adress ?? "")
                self?.timeLabel.text = "预约时间: " + (model?.appointmentTime ?? "")
                self?.isEyeRedLabel.text = "眼睛是否红、肿、痛: " + (model?.isEyeRed == 1 ?"有":"无")
                self?.isSecretionLabel.text = "有无分泌物: " + (model?.isSecretion == 1 ?"有":"无")
                self?.isTrichiasisLabel.text = "睫毛有无倒睫: " + (model?.isTrichiasis == 1 ?"有":"无")
                self?.isUnobstructedLabel.text = "泪道是否通畅: " + (model?.isUnobstructed == 1 ?"通畅":"不通畅")
                self?.isSutureLabel.text = "眼部是否有缝线: " + (model?.isSuture == 1 ?"有":"无")
                self?.projectTitleLabel.text = model?.projectTitle ?? ""
                

                
                
                //总金额
                let moneyString : String = String(format: "%.2f", (model?.orderAmount.floatValue)! / 100)
                
                let sumMoneyString = NSMutableAttributedString(
                    string: "合计：" +  moneyString + "元",
                    attributes: [NSAttributedString.Key.font:
                        UIFont(name: "PingFangSC-Semibold", size: 14.0)!])
                sumMoneyString.addAttribute(NSAttributedString.Key.foregroundColor,value:UIColor(hex: "#F54C4C"), range: NSRange(location: 3,length: moneyString.count))
                
                self?.sumMoneyLabel?.attributedText = sumMoneyString
                
                
                
                
                //交通费
                let freightString : String = String(format: "%.2f", (model?.fare.floatValue)! / 100)
                
                let freightMoneyString = NSMutableAttributedString(
                    string: "含交通费" +  freightString + "元",
                    attributes: [NSAttributedString.Key.font:
                        UIFont(name: "PingFang SC", size: 12.0)!])
                freightMoneyString.addAttribute(NSAttributedString.Key.foregroundColor,value:UIColor(hex: "#FBAF57"), range: NSRange(location: 4,length: freightString.count))
                
                self?.freightLabel?.attributedText = freightMoneyString
                
                
                
                
                //护士名称
                self?.nurseNameLabel.attributedText = YSGNurseAppointmentOrderModel.getNurseName(model?.nurseName ?? "")
                
                
                
                //底部视图
                switch model?.appointmentStatus {
                case .reserved,.completed:
                    self?.tableView.tableFooterView = self?.tableViewBottomView
                    self?.tableViewBottomLabel.attributedText = self?.viewModel.getSumMoneyAttributedString()
                    self?.nurseView.isHidden = false
                case .evaluated:
                    self?.nurseView.isHidden = false
                    self?.tableView.tableFooterView = self?.starRatingView
                    self?.starRatingView.starRatingView.currentStarCount = (model?.commentScore?.floatValue ?? 0)
                    self?.starRatingView.textView?.text = model?.commentContent ?? "无评价内容"
                case .unpaid:
                    self?.nurseView.isHidden = true
                case .notApproved_unassigned,.notApproved_missedOrders:
                    self?.tableView.tableFooterView = self?.tableViewBottomView
                    self?.tableViewBottomLabel.attributedText = self?.viewModel.getSumMoneyAttributedString()
                    self?.nurseView.isHidden = true
                default:
                    self?.tableView.tableFooterView = UIView(frame: CGRect.zero)
                    self?.nurseView.isHidden = true
                }
                
                //是否从列表点进来
                if self?.isListPay as! Bool {
                    self?.payAction()
                    self?.isListPay = false
                }
      
            }
                
        }
    }
    
    @IBAction func phoneCallAction(_ sender: Any) {
        UIApplication.shared.openURL(URL(string: "telprompt://" + (model?.nursePhone ?? "") )!)
    }
    
    private func setupNotification() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPaySuccess(_:)),
                                               name: NotiName.wechatPaySuccess,
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPayFailure(_:)),
                                               name: NotiName.wechatPayFailure,
                                               object: nil)
    }
    

    
    @IBAction func payAction() {
        
        
        if !agreeButton.isSelected {
            HUDTool.showError(message: "请阅读并同意患者协议")
            return
        }
        
        payButton?.isUserInteractionEnabled = false
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.payButton?.isUserInteractionEnabled = true
        }
        generateOrder(orderId ?? "", String(format: "%.0f", (self.model?.orderAmount.floatValue ?? 0)))
        
    }
    func generateOrder(_ _orderId : String, _ _orderAmount : String) {
        
        HUDTool.showActivity()
        
        WXApiRequestHandler.wxPaySubmitOrder(orderId:
                                                _orderId
                                             , orderAmount:_orderAmount, orderType: .nurse) {(wxModel) in
            HUDTool.hideActivity()
            switch wxModel.getType {
            case 1:
                self.showSelectPayStyleView(wxModel)
            case 4:
                HUDTool.show(message: "医保已全额支付")
                self.pushPayResultVc()
            default:
                break
            }
        } failure: { (errorMsg, code) in
            HUDTool.showError(message: errorMsg)
        }
    }
    

        
        

    /// 选择支付方式
    private func showSelectPayStyleView(_ model: WXPayResult) {
        let styleView = UINib.loadViewFrom(SelectPayStyleView.self)
        styleView.show()
        
        styleView.configure(cost: String    (format: "%.2f", (model.ownAmount.floatValue )/100), time: "30")
        styleView.handlerClosure = {style in
            switch style {
            case .wechat:
                self.wechatPay(model)
            }
        }
        styleView.cancelClosure = {
        }
    }
    
    
    /// 微信支付
    private func wechatPay(_ model: WXPayResult) {
        if !WXApi.isWXAppInstalled() {
            HUDTool.show(message: "未安装微信")
            return
        }
        
        WXApiRequestHandler.generateWXPayOrder(model: model)
    }
    
    @objc private func wechatPaySuccess(_ noti: Notification) {
        HUDTool.showActivity()
        PayViewModel.queryOrderStatus(orderId: orderId ?? "") {[weak self] (errorMsg) in
            HUDTool.hideActivity()
            if errorMsg != nil {
                HUDTool.show(message: "订单支付失败")
                return
            }
        
            switch self?.model?.appointmentStatus{
            case .unpaid:
                self?.pushPayResultVc()
            default:
                HUDTool.show(message: "辅材支付成功")
                self?.tableView.mj_header?.beginRefreshing()
            }
   
        }
    }
    
    @objc private func wechatPayFailure(_ noti: Notification) {
        HUDTool.show(message: "订单支付失败")
    }
    
    private func pushPayResultVc() {
        let payResultVc = PayResultViewController(with: PublishViewModel(), orderType: .nurse)
        removeCurrentVcWhenPush(payResultVc)
    }

    
    
    private lazy var evaluateView: YSGNurseAppointMentStarRatingView = {
        evaluateView = UINib.loadViewFrom(YSGNurseAppointMentStarRatingView.self)
        return evaluateView
    }()
    
}



extension YSGNurseAppointmentOrderDetailsController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return (viewModel.consumeMaterialsDic?.keys.count ?? 0) >  0 ? 1 : 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.consumeMaterialsDic?.keys.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YSGNurseAppointmentConsumablesCell.reuseIdentifier(),
                                                 for: indexPath) as! YSGNurseAppointmentConsumablesCell
        cell.delegate = self
        cell.configure(viewModel.consumeMaterialsDic?[viewModel.consumeMaterialsArray[indexPath.row]] as! Array<YSGNurseAppointmentInfoConsumablessModel>)
        cell.selectionStyle = .none;
        return cell
    }
}

extension YSGNurseAppointmentOrderDetailsController: UITableViewDelegate,YSGNurseAppointmentConsumablesCellDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return tableViewHeaderView
    }
    

    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(viewModel.rowHeight(indexPath.row))
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 51
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func pay(_ _orderId: String,_ _orderAmount: String){
        generateOrder(_orderId, _orderAmount)
    }
}
